﻿using System;
using System.Linq;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.DynamicData;
using NotAClue.Web;
using NotAClue.Web.DynamicData;
using NotAClue.ComponentModel.DataAnnotations;

namespace DD_Extensions
{
    public partial class MultiColumnEntityTemplate : System.Web.DynamicData.EntityTemplateUserControl
    {
        private const string COLUMNS = "Columns";
        private const string TITLE_CSS_CLASS = "TitleCssClass";
        private const string FIELD_CSS_CLASS = "FieldCssClass";

        protected override void OnLoad(EventArgs e)
        {
            // get columns from table
            var metaColumns = Table.GetScaffoldColumns(Mode, ContainerType).ToList();

            // do not render any HTML table if there are no columns returned
            if (metaColumns.Count == 0)
                return;

            // default the HTML table columns and CSS class names
            int columns = 2;
            String titleCssClass = "DDLightHeader";
            String fieldCssClass = String.Empty;

            // Get the CssClass for the title & Field from the attribute
            var entityUHint = Table.GetAttribute<EntityUIHintAttribute>();
            if (entityUHint != null)
            {
                if (entityUHint.ControlParameters.Keys.Contains(COLUMNS))
                    columns = (int)entityUHint.ControlParameters[COLUMNS];
                if (entityUHint.ControlParameters.Keys.Contains(TITLE_CSS_CLASS))
                    titleCssClass = entityUHint.ControlParameters[TITLE_CSS_CLASS].ToString();
                if (entityUHint.ControlParameters.Keys.Contains(FIELD_CSS_CLASS))
                    fieldCssClass = entityUHint.ControlParameters[FIELD_CSS_CLASS].ToString();

                //<td colspan="2" class="CommandCell">
                //$("TD.CommandCell").attr("colSpan", 3);
                var colSpan = entityUHint.ControlParameters.GetControlParameter<int>(COLUMNS);
                if (colSpan > 0)
                {
                    var script = String.Format("$(\"TD.CommandCell\").attr(\"colSpan\", {0});\n", colSpan);
                    Page.AddStartupClientScript(Table.Name, script);
                }
            }

            // start in the left column
            int col = 0;

            // create the header cell
            var headerRow = new HtmlTableRow();
            if (!String.IsNullOrEmpty(titleCssClass))
                headerRow.Attributes.Add("class", titleCssClass);

            // create the data cell
            var dataRow = new HtmlTableRow();
            if (!String.IsNullOrEmpty(fieldCssClass))
                dataRow.Attributes.Add("class", fieldCssClass);

            var th = new HtmlTableCell();
            var td = new HtmlTableCell();

            // step through each of the columns to be added to the table
            foreach (var metaColumn in metaColumns)
            {
                // get the MultiColumn attribute for the column
                var multiColumn = metaColumn.GetAttributeOrDefault<MultiColumnAttribute>();
                if (multiColumn.ColumnSpan > columns)
                    throw new InvalidOperationException(String.Format("MultiColumn attribute specifies that this field occupies {0} columns, but the EntityUIHint attribute for the class only allocates {1} columns in the HTML table.", multiColumn.ColumnSpan, columns));

                // check if there are sufficient columns left in the current row
                if (col + multiColumn.ColumnSpan > columns)
                {
                    for (int i = col; i < columns; i++)
                    {
                        th = new HtmlTableCell();
                        headerRow.Cells.Add(th);
                        td = new HtmlTableCell();
                        dataRow.Cells.Add(td);
                    }

                    // save this header 
                    this.Controls.Add(headerRow);

                    // create new header 
                    headerRow = new HtmlTableRow();
                    if (!String.IsNullOrEmpty(titleCssClass))
                        headerRow.Attributes.Add("class", titleCssClass);

                    // save this data 
                    this.Controls.Add(dataRow);

                    // create new data 
                    dataRow = new HtmlTableRow();
                    if (!String.IsNullOrEmpty(fieldCssClass))
                        dataRow.Attributes.Add("class", fieldCssClass);

                    // need to start a new row
                    col = 0;
                }

                // add the header cell
                th = new HtmlTableCell();
                var label = new Label();
                label.Text = metaColumn.DisplayName;

                th.InnerText = metaColumn.DisplayName;
                if (multiColumn.ColumnSpan > 1)
                    th.ColSpan = multiColumn.ColumnSpan;
                headerRow.Cells.Add(th);

                // add the data cell
                td = new HtmlTableCell();
                var dynamicControl = new DynamicControl(Mode)
                {
                    DataField = metaColumn.Name,
                    ValidationGroup = this.ValidationGroup
                };

                td.Controls.Add(dynamicControl);

                if (multiColumn.ColumnSpan > 1)
                    td.ColSpan = multiColumn.ColumnSpan;

                dataRow.Cells.Add(td);

                // record how many columns we have used
                col += multiColumn.ColumnSpan;
            }

            if (col < columns)
            {
                for (int i = col; i < columns; i++)
                {
                    th = new HtmlTableCell();
                    headerRow.Cells.Add(th);
                    td = new HtmlTableCell();
                    dataRow.Cells.Add(td);
                }
            }

            this.Controls.Add(headerRow);
            this.Controls.Add(dataRow);
        }
    }
}
